from flask import Flask, render_template, send_from_directory, jsonify
from flask_socketio import SocketIO
from flask import request
import mysql.connector
import json
import random
import time

# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_url_path='')


@app.route('/<path:path>')
def static_file(path):
    return send_from_directory('static', path)


app.config['SECRET_KEY'] = 'vnkdjnfjknfl1232#'
socketio = SocketIO(app)
msg_channel = "msg_channel"
properties = {}


@app.route('/')
def sessions():
    return render_template('session.html')


@app.route('/log')
def fetch_log(methods=['GET']):
    db = conn()
    cur = db.cursor(buffered=True)
    sql = "select timestamp, ip, msg from log order by timestamp desc limit 8"
    cur.execute(sql)
    result = cur.fetchall()
    db.commit()
    db.close()
    return jsonify(result)


def messageReceived(methods=['GET', 'POST']):
    print('message was received!!!')


@socketio.on(msg_channel)
def handle_msg(json, methods=['GET', 'POST']):
    json['ip'] = request.remote_addr
    if 'msg' not in json:
        return
    socketio.emit(msg_channel, json)

    db = conn()
    cur = db.cursor(buffered=True)
    ip = json['ip']
    msg = json['msg']
    sql = "INSERT INTO log" \
        " (timestamp, ip, msg) " \
        f"VALUES (\"{timestamp()}\", \"{ip}\", \"{msg}\")"
    cur.execute(sql)
    cur.close()
    db.commit()
    db.close()


def conn():
    global properties
    host = properties['mysql']['host']
    user = properties['mysql']['user']
    passwd = properties['mysql']['passwd']
    database = properties['mysql']['database']

    return mysql.connector.connect(host=host, user=user,
                                   passwd=passwd, database=database)


def prop():
    global properties
    f = open('properties.json', encoding='utf-8')
    properties = json.load(f)
    f.close()
    # print(json.dumps(properties))
    return properties


def timestamp():
    s = time.strftime('%Y%m%d%H%M%s', time.localtime())
    s += "%s%s" % (s, str(random.randint(0, 1024)))
    return s


if __name__ == '__main__':
    # sys.argv[1:]
    properties = prop()
    socketio.run(app, debug=True)
